import { _decorator, Node, Sprite, SpriteFrame } from "cc";
import { ItemType } from "../model";
import { RenderManager } from "../base/render-manager";
import { BackPackManager } from "../back-pack-manager";
const { ccclass, property } = _decorator;

@ccclass("BaseItemManager")
export class BaseItemManager extends RenderManager {
  @property({ type: SpriteFrame, tooltip: "游戏场景中显示的图片" })
  public spriteInScene: SpriteFrame = null;

  @property({ type: SpriteFrame, tooltip: "游戏场景中显示的图片" })
  public spriteInPack: SpriteFrame = null;

  protected itemType: ItemType = null;

  get isInScene() {
    return BackPackManager.Instance.isItemInScene(this.itemType);
  }

  onLoad() {
    super.onLoad();
    this.node.on(Node.EventType.TOUCH_END, this.onItemClick, this);
  }

  protected onDestroy(): void {
    super.onDestroy();
    this.node.off(Node.EventType.TOUCH_END, this.onItemClick, this);
  }

  onItemClick() {
    if (this.isInScene) {
      BackPackManager.Instance.collectItem(this.itemType);
    }
  }

  render(): void {
    const item = BackPackManager.Instance.getItemByType(this.itemType);
    if (!item || item.used) {
      this.node.active = false;
      return;
    }
    console.log(item);
    const spriteComponent = this.node.getComponent(Sprite);
    spriteComponent.spriteFrame = item.collected
      ? this.spriteInPack
      : this.spriteInScene;
  }
}
